package com.deepinblog.oosdemo.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.deepinblog.oosdemo.bean.UpLoadResult;
import com.deepinblog.oosdemo.config.AliyunConfig;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUpLoadService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient ossClient;
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".jpg",
            ".jpeg", ".png"};

    public UpLoadResult upload(MultipartFile multipartFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }


        UpLoadResult upLoadResult = new UpLoadResult();
        if (!isLegal) {
            upLoadResult.setStatus("仅仅支持" + ".jpg"+
                    ".jpeg"+ ".png");
            return upLoadResult;
        }

        if (!onSize(multipartFile)) {
            upLoadResult.setStatus("图片大小不能超过5M");
            return upLoadResult;

        }


        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        upLoadResult.setUid(filePath);
        return upLoadResult;
    }
    // 生成不重复的文件路径和文件名
    /*private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }*/

    private String getFilePath(String sourceFileName) {
        return "images/" + UUID.randomUUID().toString() + "." + sourceFileName;
    }

    public void download(String name, HttpServletRequest request, HttpServletResponse response) {

        try {

            OSSObject object = ossClient.getObject(aliyunConfig.getBucketName(), name);
            response.setHeader("Content-Disposition", "attachment; filename=" + name);

            InputStream objectContent = object.getObjectContent();

            ServletOutputStream outputStream = response.getOutputStream();


            int len = 0;
            byte[] bts = new byte[1024];
            while ((len = objectContent.read(bts)) != -1) {
                outputStream.write(bts, 0, len);
            }


        } catch (Exception e) {
            e.printStackTrace();

        }


    }

    public UpLoadResult delete(String name, HttpServletRequest request, HttpServletResponse response) {

        UpLoadResult upLoadResult = new UpLoadResult();

        try {
            ossClient.deleteObject(aliyunConfig.getBucketName(), name);
        } catch (Exception e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return upLoadResult;
        }
        upLoadResult.setStatus("Delete successfully");

        return upLoadResult;
    }


    private boolean onSize(MultipartFile mf) {


        if (mf.getSize() >= 1024 * 1000 * 5) {
            return false;
        }

        return true;
    }


    private String getSuffix(MultipartFile file) {
        return file.getContentType().split("/")[1];
    }
}
